#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/12 16:40
# @Author  : huidong.bai
# @File    : serializers.py
# @Software: PyCharm

from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from .models import TaskModel, TaskModuleModel, TaskCaseModel
from user.models import User
from testcase.models import SpeakerProduct
from testcase.models import TestCase


class TaskModelSerializer(ModelSerializer):
    class Meta:
        model = TaskModel
        fields = ["title", "task_type", "creator", "is_smoke", "desc"]


class TaskModuleSerializer(ModelSerializer):
    class Meta:
        model = TaskModuleModel
        fields = ["module"]


class TaskSerializer(ModelSerializer):
    creator = serializers.SerializerMethodField()
    task_type = serializers.SerializerMethodField()
    create_time = serializers.SerializerMethodField()
    modules = serializers.SerializerMethodField()
    sys_version = serializers.SerializerMethodField()

    class Meta:
        model = TaskModel
        fields = [
            "id",
            "title",
            "task_type",
            "create_time",
            "is_smoke",
            "creator",
            "start_time",
            "end_time",
            "pass_rate",
            "progress",
            "desc",
            "test_speaker",
            "modules",
            "sys_version",
            "status"
        ]

    def get_task_type(self, obj):
        return SpeakerProduct.objects.get(id=obj.task_type_id).speaker_name

    def get_creator(self, obj):
        return User.objects.get(id=obj.creator_id).nick_name

    def get_create_time(self, obj):
        return TaskModel.objects.get(id=obj.id).create_time.strftime("%Y-%m-%d %H:%M:%S")

    def get_modules(self, obj):
        modules = []
        objs = TaskModuleModel.objects.filter(task_id=obj.id)
        for obj in objs:
            modules.append(obj.module.module_name)
        return modules

    def get_sys_version(self, obj):
        return SpeakerProduct.objects.get(id=obj.task_type_id).system_version
